package cn.weekimwee.firstlineofcodeforkotlin.unit6

import android.content.Context
import android.os.Bundle
import android.view.View
import cn.weekimwee.firstlineofcodeforkotlin.BaseActivity
import cn.weekimwee.firstlineofcodeforkotlin.R
import kotlinx.android.synthetic.main.activity_save_file.*
import java.io.*
import java.lang.StringBuilder

class SaveFileActivity : BaseActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_save_file)
        save.setOnClickListener { it.onClick() }
        show.setOnClickListener { it.onClick() }
    }

    private fun View.onClick() {
        when (this.id) {
            R.id.save -> {
                saveFile(edit.text.toString())
            }
            R.id.show -> {
                showText()
            }
        }
    }

    private fun showText(){
        var reader:BufferedReader?=null
        var content = StringBuilder()
        try {
            reader = BufferedReader(InputStreamReader(openFileInput("data")))
            reader.readLine().forEach {
                content.append(it)
            }
            text.text = content.toString()
        }catch (e:IOException){
            e.printStackTrace()
        }finally {
            try {
                reader?.let {
                    reader.close()
                }
            }catch (e:IOException){
                e.printStackTrace()
            }
        }
    }

    private fun saveFile(content: String){
        var writer:BufferedWriter?=null
        try {
            writer = BufferedWriter(OutputStreamWriter(openFileOutput("data", Context.MODE_APPEND)))
            writer.write(content)
        }catch (e:IOException){
            e.printStackTrace()
        }finally {
            try {
                writer?.close()
            }catch (e :IOException){
                e.printStackTrace()
            }
        }
    }
}
